<template>
	<div class="content">
		<mt-header fixed :title="coursename+'错题本'">
			<mt-button icon="back" @click="_back" slot="left"></mt-button>
		</mt-header>
		<div v-if="view=='wrong'">
			<!--<div class="nav">
			<div id="myChart" :style="{width: '375px', height: '250px'}"></div>
		</div>-->
			<!--<div class="listNav">
			<span>错题列表</span>
			<select name="" id="">
				<option value="" class="moren">知识点</option>
				<option v-for="item in knowledgeObj.Xkey" :value="item">{{ item }}</option>
			</select>
		</div>-->
			<div id="wrongList" class="page-loadmore-wrapper" ref="wrapper" :style="{ height: wrapperHeight + 'px' }">
				<mt-loadmore :bottom-method="loadBottom" :bottomLoadingText='bottomLoadingText' @bottom-status-change="handleBottomChange" :bottom-all-loaded="allLoaded" ref="loadmore">
					<ul>
						<li v-for="(x,index) in wrongList">
							<p>—&nbsp;&nbsp;{{ x.day }}&nbsp;&nbsp;—</p>
							<div v-for="(item, $index) in x.mistakes">
								<div v-html="item.body" class="quesBox" @click="openQues(item)"></div>
								<div class="foot">
									<div class="right" @click="deleteQues(item,index,$index)"></div>
								</div>
							</div>
						</li>
					</ul>
				</mt-loadmore>
			</div>
		</div>
		<div v-if="view=='question'" class="quesContent">
			<div v-html="currentQues.body"></div>
			<div class="answer">
				<div class="left">
					<span>{{ transAnswer(currentQues.answer) }} </span> 正确答案
				</div>
				<div class="right">

					<span class="wrong">{{ transAnswer(currentQues.wrongkey) }}</span> 我的答案
				</div>
			</div>
			<h4>解析：</h4>
			<div v-html="currentQues.analysis"></div>
			<div class="foot">
				<!--<div class="videoKnowledge">相关视频</div>-->
				<div class="consolidation" @click="consolidation">巩固练习</div>
			</div>
		</div>
	</div>
</template>

<script>
	import api from '../../api';
	import $ from 'jquery'
	import { mapState, mapMutations } from "vuex";
	import { Loadmore, Indicator } from 'mint-ui';
	import { subjectMatch } from '../../util/util';
	let echarts = require('echarts/lib/echarts');
	// 引入柱状图组件
	require('echarts/lib/chart/bar')
	// 引入提示框和title组件
	require('echarts/lib/component/tooltip')
	require('echarts/lib/component/title')
	export default {
		data() {
			return {
				courseid: '',
				day: '',
				codeid: '',
				coursename: '',
				codeArr: [],
				dayInterval: 3,
				knowledgeObj: {},
				wrongList: [],
				view: 'wrong',
				currentQues: {},
				mistakeTidsList: [],
				currentWrongIndex: 0,
				allLoaded: false,
				bottomStatus: '',
				wrapperHeight: 0,
				bottomLoadingText:'加载中'
			}
		},
		mounted() {
			this.wrapperHeight = document.documentElement.clientHeight - this.$refs.wrapper.getBoundingClientRect().top + 44;
		},
		created() {
			var that = this
			Indicator.open({
				text: 'Loading...',
				spinnerType: 'triple-bounce'
			});
			this.INIT_STATE()
			this.view = 'wrong';
			this.courseid = this.$route.params.subject_type;
			this.coursename=subjectMatch(this.$route.params.subject_type)
			api.getStudentMistakesListIdsOfCourse({
				studentid: this.userlogin.uid,
				courseid: this.courseid,
				dayfrom: 0,
				dayto: 0
			}).then(response => {
					Indicator.close();
				//2018-1-31目前后台无法完成分页，顾有前端先做分页ε=(´ο｀*)))唉
				that.mistakeTidsList = that.split_Arr(response.data.data, 10)
				that.getSubjectWrongData()
			})
			$(function() {
				var h = document.body.clientHeight;
				$('.content').css({'min-height':h - 44+ 'px','padding-bottom':'0px'})
			})
		},
		activated() {
			this.view = 'wrong';
			$('.content').css({'padding-bottom':'0px'})
		},
		computed: {
			...mapState(["exerciseInfo", "userlogin"])
		},
		watch: {
			wrongList: function() {

			}
		},
		methods: {
			...mapMutations(["INIT_STATE", "EXERCISE_ADD"]),
			_back() {
				console.log(this.view)
				if(this.view == 'wrong') {
					window.history.back()
				} else {
					this.view = 'wrong'
					var h = document.body.clientHeight;
					$('.content').css({'min-height':h - 44+ 'px','padding-bottom':'0px'})
				}
			},
			handleBottomChange(status) {
				console.log(status)
				this.bottomStatus = status;
			},
			loadBottom() {
				setTimeout(() => {
					if(this.currentWrongIndex < this.mistakeTidsList.length - 1) {
						this.currentWrongIndex++
						this.getSubjectWrongData()
					} else {						
						this.bottomLoadingText='没有更多了'
					}
					this.$refs.loadmore.onBottomLoaded();
				}, 1500);
			},
			getSubjectWrongData() {
				var that = this;
				var nowDate = new Date();
				var dayto = '' + nowDate.getFullYear() + this.toTwo(nowDate.getMonth() + 1) + nowDate.getDate()
				var oldDate = new Date(nowDate.getTime() - this.dayInterval * 24 * 60 * 60 * 1000)
				var dayfrom = '' + oldDate.getFullYear() + this.toTwo(oldDate.getMonth() + 1) + oldDate.getDate()
				
				api.getSubjectWrong({
					courseid: this.courseid,
					studentid: this.userlogin.uid,
					mids: this.mistakeTidsList[this.currentWrongIndex].join(',')
				}).then(response => {
					Indicator.close();
					var out = response.data.data
					var arr = out.mistakesList
					arr.sort(function(a,b){
						return parseInt(b.day)-parseInt(a.day)
					})
					console.log(arr)
					arr.forEach(function(v, i) {
						console.log(v.day)
						arr[i].day = v.day.substr(0, 2) + '月' + v.day.substr(2, 4) + '日'
						arr[i].ids = v.mistakes.map(function(x) {
							return x.testid
						})
						that.getQues(0, v.mistakes)
						//						v.mistakes.forEach(function(item,index){
						//							api.getListQuestionById(item.testid).then(response=>{
						//								item=Object.assign({},item,response.data.datalist[0])								
						//								console.log(that.wrongList)
						//							})
						//						})
					})
					that.wrongList = that.wrongList.concat(arr)

					//					that.knowledgeObj['Xkey'] = out.knowledgeList.map(function(item) {
					//						return item.codename
					//					});
					that.knowledgeObj['Xkey'] = ['有理数', '数轴', '相反数', '绝对数', '乘方']
					//					that.knowledgeObj['Yvalue'] = out.knowledgeList.map(function(item) {
					//						return item.num
					//					});
					that.knowledgeObj['Yvalue'] = [2, 2, 3, 5, 7]
					//					that.drawLine()
				})
			},
			getQues(index, arr) {
				var that = this;
				api.getListQuestionById(arr[index].testid).then(response => {
					that.$set(arr[index], 'body', response.data.datalist[0].body)
					index++
					if(index < arr.length) {
						that.getQues(index, arr)
					}
				})
			},
			openQues(item) {
				var that = this
				api.getListQuestionById(item.testid).then(response => {
					that.currentQues = Object.assign({}, item, response.data.datalist[0])
					console.log(that.currentQues)
					that.view = "question"
					var h = document.body.clientHeight;
					$('.content').css({'min-height':h - 44-50 + 'px','padding-bottom':'50px'})
				
				})
			},
			consolidation() {
				this.EXERCISE_ADD({
					source_url:'/wrongbook/'+this.courseid,
					category_id: this.currentQues.categoryid,
					level_id: this.currentQues.level,
					courseid: this.currentQues.courseid,
					typeid: this.currentQues.typeid,
					coursename: this.currentQues.coursename
				});
				this.$router.push({
					path: '/exercise'
				})
			},
			deleteQues(item, index, $index) {
				var that = this
				api.deleteMistakes({
					studentid: item.studentid,
					mid: item.mid,
					day: item.day
				}).then(response => {
					that.wrongList[index].mistakes.splice($index, 1)
					if(that.wrongList[index].mistakes.length == 0) {
						that.wrongList.splice(index, 1)
					}
				})
			},
			toTwo(num) {
				var num = Number(num)
				if(num >= 10) {
					return num
				} else {
					return '0' + num
				}
			},
			drawLine() {
				var that = this;
				// 基于准备好的dom，初始化echarts实例
				let myChart = echarts.init(document.getElementById('myChart'))
				// 绘制图表
				myChart.setOption({
					title: {
						text: '错题统计',
						textStyle: {
							color: '#FA8C13',
							fontSize: '14px'
						}
					},
					tooltip: {},
					grid: {
						left: '15%',
						top: '30'
					},
					xAxis: {
						data: that.knowledgeObj['Xkey']
					},
					yAxis: [{
						type: 'value',
						show: true
					}],
					series: [{
						name: '参与率',
						type: 'bar',
						itemStyle: {
							normal: {
								color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
										offset: 0,
										color: '#FAD961'
									},
									{
										offset: 1,
										color: '#F76B1C'
									}
								])
							}
						},
						data: that.knowledgeObj['Yvalue'],
						barWidth: '19px'
					}]
				});
			},
			split_Arr(arr, len) {
				var result = [];
				for(var i = 0; i < arr.length; i += len) {
					result.push(arr.slice(i, i + len))
				}
				return result
			},
			transAnswer(ans){
				if(ans.indexOf('正确')>-1||ans=='R'||ans.indexOf('对')>-1){
					return '√';	
				}else if(ans.indexOf('错误')>-1||ans=='W'||ans.indexOf('错')>-1){
					return 'X';					
				}else{
					return ans
				}
			}			
		}
	}
</script>

<style scoped>
	.page-loadmore-wrapper {
		overflow: scroll
	}
	
	select {
		/*Chrome和Firefox里面的边框是不一样的，所以复写了一下*/
		border: solid 1px #000;
		/*很关键：将默认的select选择框样式清除*/
		appearance: none;
		-moz-appearance: none;
		-webkit-appearance: none;
		/*在选择框的最右侧中间显示小箭头图片*/
		background: url(../../assets/images/select.png) no-repeat scroll right center transparent;
		background-size: 14px;
		/*为下拉小箭头留出一点位置，避免被文字覆盖*/
		padding-right: 14px;
	}
	
	.listNav {
		text-align: left;
		font-size: 14px;
		color: #FA8C13;
		text-indent: 12px;
		padding-top: 15px;
	}
	
	.listNav select {
		float: right;
		height: 25px;
		text-indent: 8px;
		margin-right: 14px;
	}
	
	.listNav select .moren {
		color: dimgray;
	}
	
	.content {
		
	}
	
	#wrongList {
		font-size: 14px;
		text-align: left;
	}
	
	#wrongList .quesBox {
		padding-top: 14px;
		padding-left: 20px;
		padding-right: 20px;
		border-top: 2px solid #f7f7f7;
	}
	
	#wrongList .foot {
		height: 30px;
		margin: 0 auto;
		padding: 0 14px;
		margin-top: -1px;
		border-top: 1px solid #f7f7f7;
	}
	
	#wrongList .foot .left {
		float: left;
		height: 26px;
		background: #E3E3E3;
		border-radius: 13px;
		color: white;
		font-size: 14px;
		margin: 2px;
		padding: 0 8px;
		line-height: 26px;
	}
	
	#wrongList .foot .right {
		float: right;
		width: 0.4rem;
		height: 0.4rem;
		background: url(../../assets/images/alter_delete.png) no-repeat scroll center;
		background-size: contain;
		margin-right: calc(50% - 0.2rem);
		margin-top: 5px;
	}
	
	ul {
		padding: 0;
		margin: 0;
	}
	
	li {
		width: 100%;
		list-style: none;
		border-top: 2px solid #f7f7f7;
	}
	li>div:nth-of-type(n+1){
		background: white;
    	margin-top: 5px;		
	}
	#wrongList li>p {
		text-align: center;
		margin: 0;
		color: #3c3c3c;
		font-weight: bold;
		font-size: 14px;
		line-height: 24px;
	}
	
	.quesContent {
		font-size: 14px;
		text-align: left;
		height: calc(100% - 90px);
		height: -webkit-calc(100% - 90px);
		height: -moz-calc(100% - 90px);
		overflow: scroll;
		padding-top: 14px;
	}
	
	.quesContent>div {
		padding: 0 18px;
	}
	
	.consolidation {
		text-align: center;
	}
	
	.quesContent h4 {
		font-weight: bold;
		font-size: 16px;
		color: cornflowerblue;
		margin-top: 21px;
		margin-bottom: 10px;
		font-size: 14px;
		color: #FA8C13;
		letter-spacing: -0.3px;
		padding-left: 18px;
	}
	
	.quesContent .answer {
		margin: 14px 18px;
		height: 59px;
		line-height: 59px;
		border: 1px dashed rgba(0, 0, 0, 0.2);
	}
	
	.quesContent .answer {
		color: #9b9b9b;
		font-size: 12px;
		display: flex;
		justify-content: space-around;
		margin-top: 15px;
	}
	
	.answer>.left>span {
		font-size: 20px;
		color: #3c3c3c;
	}
	
	.answer>.right>span.wrong {
		font-size: 20px;
		color: #F65D5D;
	}
	
	.answer span {
		color: white;
		margin-right: 12px;
	}
	
	.quesContent .foot {
		position: fixed;
		display: flex;
		justify-content: flex-start;
		bottom: 0;
		height: 50px;
		font-size: 16px;
		color: #FFFFFF;
		background: #1382FA;
		box-shadow: 0 0 2px 0 rgba(0, 0, 0, 0.30);
		width: 100%;
		padding: 0;
		line-height: 50px;
	}
	
	.quesContent .foot div {
		width: 100%;
		text-align: center;
	}
	
	.quesContent .foot div.videoKnowledge {
		background: #FA8C13;
	}
</style>